<template>
  <div class="app-content-map" ref="content-map">
    <div class="task-type">
      <a-select style="width: 220px" @change="SelectType" allowClear v-model="task_type">
        <a-select-option
          :value="item.typevalue"
          v-for="(item, index) in $store.state.task_types"
          :key="index"
        >{{ item.typename }}</a-select-option>
      </a-select>
    </div>
    <!-- v-show="activeTasks.length>0" -->
    <show_png></show_png>
    <div id="task3" style="border: 2px solid gray">
      <h3>判读成果质检。用户列表如拉取不成功需多次尝试</h3>
      <a-select style="width: 160px" @change="taskSelectChange" allowClear v-model="activeTask">
        <a-select-option
          :value="item.mergeid"
          v-for="(item, index) in activeTasks"
          :key="index"
        >{{ item.name }}</a-select-option>
      </a-select>
      <a-row style="margin: 5px">
        <a-radio-group v-model="currentOrg" @change="onChangeOrg" style="margin: 5px 0">
          <a-radio-button value="2c9380847d93d128017da245e4434b10">地图院</a-radio-button>
          <a-radio-button value="2c9380847b7619f5017b8ab867951580">申科</a-radio-button>
        </a-radio-group>
        <a-select style="width: 160px" @change="NameSelectChange" allowClear v-model="selectedName">
          <a-select-option
            :value="item.fullname"
            v-for="(item, index) in userNames"
            :key="index"
          >{{ item.fullname }}</a-select-option>
        </a-select>
        <a-button type="primary" @click="fetchUserNames">获取用户列表</a-button>
        <a-radio-group v-model="resultType" @change="onChangeResultType" style="margin: 5px 0">
          <a-radio-button value="1">未变化</a-radio-button>
          <a-radio-button value="2">已变化</a-radio-button>
          <a-radio-button value="-1">未判读</a-radio-button>
        </a-radio-group>
        <a-space>
          <a-select style="width: 220px" @change="SelectType" allowClear v-model="task_type">
            <a-select-option
              :value="item.typevalue"
              v-for="(item, index) in $store.state.task_types"
              :key="index"
            >{{ item.typename }}</a-select-option>
          </a-select>
          <a-button type="primary" @click="getAllData">查看进度汇总</a-button>
        </a-space>
      </a-row>
      <a-modal v-model="modalVisible" title="当前进度查看" @ok="handleOk" :width="800">
        <!-- 总判读进度 <a-progress type="circle" :percent="75" /> -->

        <a-table :columns="columns" :data-source="userTables">
          <span
            slot="total"
            slot-scope="text, record"
          >{{ record.data.unfinish + record.data.changed + record.data.nochange }}</span>
          <span slot="rate" slot-scope="text, record">
            <!-- {{record.data.changed/(record.data.changed+record.data.nochange)*100}}%  -->
            <a-progress
              :percent="Math.round(record.data.changed / (record.data.changed + record.data.nochange) * 10000) / 100"
              size="small"
            />
          </span>
          <span slot="progress" slot-scope="text, record">
            <a-progress
              :percent="Math.round((record.data.changed + record.data.nochange) / (record.data.unfinish + record.data.changed + record.data.nochange) * 10000) / 100"
              size="small"
            />
          </span>
        </a-table>
      </a-modal>
      <a-row style="margin: 5px" v-show="activeTasks.length > 0">
        <a-space>
          <a-select
            style="width: 280px"
            @change="TaskSelectChange"
            v-model="activeTask"
            option-label-prop="label"
          >
            <a-select-option
              :label="item.name"
              :value="item.mergeid"
              v-for="(item, index) in activeTasks"
              :key="index"
            >{{ item.name }}</a-select-option>
          </a-select>
        </a-space>
      </a-row>
      <a-row style="margin: 5px" v-show="activeTasks.length > 0">
        <!-- <a-checkbox @change="onChange_auto" style="margin-left: 40px;" autoFocus="false" ref="Change_auto" :checked="auto_next">自动下一个</a-checkbox> -->
        <!-- <a-tooltip placement="bottom" style="margin-left: 5px;">
          <template slot="title"><span>不使用下一个按钮自动切换下一个</span></template>
          <a-icon type="question-circle" />
        </a-tooltip>-->
        <!-- </a-space> -->
        <a-pagination
          v-model="currentPage"
          defaultPageSize="49"
          :total="totalRecords"
          @change="changePage"
        />
        当前类别总条数：{{ totalRecords }}
      </a-row>
      <div class="result-op c-container new-pmd xpath-log" v-show="activeTasks.length > 0">
        <div class="op-calendar-pc">
          <div class="op-calendar-pc-box">
            <div class="op-calendar-pc-left">
              <div class="op-calendar-pc-table-box">
                <table class="op-calendar-pc-table">
                  <tbody>
                    <tr v-for="(itemTr, indexTr) in HandlData" :key="indexTr">
                      <td v-for="(itemTd, indexTd) in itemTr" :key="indexTd">
                        <div class="op-calendar-pc-relative" @click="nextFeatrue(itemTd.key)">
                          <a
                            href="javascript:void(0);"
                            :class="[
                              doKey == itemTd.key
                                ? 'op-calendar-pc-table-today'
                                : '',
                            ]"
                          >
                            <span
                              :class="[
                                'op-calendar-pc-daynumber',
                                itemTd.properties.status >= 0 ? 'checked' : '',
                              ]"
                            >{{ itemTd.key + 1 }}</span>
                            <a-icon
                              :type="
                                itemTd.properties.status == 2
                                  ? 'check'
                                  : itemTd.properties.status == 1
                                    ? 'close'
                                    : 'question'
                              "
                              :class="[
                                'op-calendar-pc-table-almanac',
                                itemTd.properties.status == 2 ? 'changed' : '',
                              ]"
                            />
                          </a>
                        </div>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
      <a-row style="margin: 5px" v-show="activeTasks.length > 0">
        <a-space>
          <!-- <a-button @click="DoPre" type="primary" :disabled="!(this.doKey>0)">上一个</a-button>
          <a-button @click="DoNext" type="primary" :disabled="!(this.doKey<this.tasks.length-1)">下一个</a-button>-->
          <!-- <a-button @click="DoUpload" type="primary" :disabled="GetStauts">提交</a-button> -->
          <!-- <a-statistic
            :value="page.count_user - page.count"
            class="demo-class"
            :suffix="`/${page.count}-${(
              ((page.count_user - page.count) / page.count_user) *
              100
            ).toFixed(1)}%`"
          >
            <template #prefix>
              <span style="font-size: 15px; color: #2c3131">解译进度:</span>
            </template>
          </a-statistic>-->
        </a-space>
      </a-row>
      <a-row v-show="activeTasks.length > 0">
        <div class="props">
          <ul>
            <li>
              <span class="values__label">AI编号</span>
              <span class="values">{{ activeTask }}</span>
            </li>
            <li>
              <span class="values__label">图斑编号</span>
              <span class="values">
                {{
                activeFeatrueProps.JVBH ? activeFeatrueProps.JVBH : ""
                }}
              </span>
            </li>
            <li>
              <span class="values__label">前期时相</span>
              <span class="values">
                {{
                activeFeatrueProps.QSX ? activeFeatrueProps.QSX : ""
                }}
              </span>
            </li>
            <li>
              <span class="values__label">前期影像</span>
              <a-tooltip placement="bottom" style="margin-left: 5px">
                <template slot="title">
                  <span>
                    {{
                    activeFeatrueProps.QQJH ? activeFeatrueProps.QQJH : ""
                    }}
                  </span>
                </template>
                <span class="values">
                  {{
                  activeFeatrueProps.QQJH ? activeFeatrueProps.QQJH : ""
                  }}
                </span>
              </a-tooltip>
            </li>
            <li>
              <span class="values__label">后期时相</span>
              <span class="values">
                {{
                activeFeatrueProps.HSX ? activeFeatrueProps.HSX : ""
                }}
              </span>
            </li>
            <li>
              <span class="values__label">后期影像</span>
              <a-tooltip placement="bottom" style="margin-left: 5px">
                <template slot="title">
                  <span>
                    {{
                    activeFeatrueProps.DQJH ? activeFeatrueProps.DQJH : ""
                    }}
                  </span>
                </template>
                <span class="values">
                  {{
                  activeFeatrueProps.DQJH ? activeFeatrueProps.DQJH : ""
                  }}
                </span>
              </a-tooltip>
            </li>
          </ul>
        </div>
      </a-row>
      <a-row v-show="activeTasks.length == 0" class="empty">
        <a-empty description="没有任务" />
      </a-row>
    </div>
    <a-drawer
      title="操作帮助"
      placement="left"
      :closable="false"
      :visible="help_visible"
      @close="helpClose"
      width="40%"
    >
      <div class="props">
        <ul>
          <li>
            <span class="values__label">1</span>
            <span class="values text">如果没有你需要做的任务则为空</span>
          </li>
          <li>
            <span class="values__label">2</span>
            <span class="values text">单图模式下空格键切换前后期影像</span>
          </li>
          <li>
            <span class="values__label">3</span>
            <span class="values text">双图模式下无需切换</span>
          </li>
          <li>
            <span class="values__label">4</span>
            <span class="values text">判译值分别为1(未变化)、2(有变化),对应快捷键数字1、2</span>
          </li>
          <li>
            <span class="values__label">5</span>
            <span class="values text">当你输入判译值时可以自动跳转</span>
          </li>
          <li>
            <span class="values__label">6</span>
            <span class="values text">Enter提交成功后自动刷新剩余的任务</span>
          </li>
        </ul>
      </div>
    </a-drawer>
  </div>
</template>
<script>

const columns = [
  {
    title: '姓名',
    dataIndex: 'username',
    key: 'username',
  },
  {
    title: '总数',
    key: 'total',
    scopedSlots: { customRender: 'total' },
  },
  {
    title: '未变化1',
    dataIndex: 'data.nochange',
    key: 'nochange',
  },
  {
    title: '已变化2',
    dataIndex: 'data.changed',
    key: 'changed',
  },
  {
    title: '未完成',
    dataIndex: 'data.unfinish',
    key: 'unfinish',
  },
  {
    title: '变化率',
    key: 'rate',
    scopedSlots: { customRender: 'rate' },
    width: 180
  },
  {
    title: '进度',
    key: 'progress',
    scopedSlots: { customRender: 'progress' },
    width: 180
  },


];
export default {
  data() {
    return {
      auto_next: true,
      //
      activeTasks: [],
      activeTask: "",
      activeFeatrueProps: {},
      tasks: [],
      HandlData: [],
      page: {},
      doKey: 0,
      tasknum: 49,
      help_visible: false,
      task_type: "bigdata",
      userNames: [],
      userTables: [],
      selectedName: "",
      resultType: "1",
      totalRecords: 49,
      currentPage: 1,
      modalVisible: false,
      columns,
      currentOrg: "2c9380847d93d128017da245e4434b10",
    };
  },
  components: {
    show_png: () => import("./show_png.vue"),
  },
  mounted() {
    this.init_keydown();
    // this.InitMap();
    setTimeout(() => {
      this.GetActiveTasks();
    }, 1000);
  },
  created() { },
  computed: {
    GetStauts() {
      if (this.tasks.length > 0) {
        let finds = this.tasks.filter((_task) => {
          return _task.properties.status < 0;
        });
        if (finds.length > 0) {
          return true;
        } else {
          return false;
        }
      } else {
        return true;
      }
    },
  },
  methods: {
    //当前页面监视键盘输入
    init_keydown() {
      let content_map = this.$refs["content-map"];
      document.onkeydown = (e) => {
        let e1 =
          e || event || window.event || arguments.callee.caller.arguments[0]; //事件对象兼容
        if (e1) {
          let keyCode = e1.keyCode;
          if (keyCode == 37) {
            //左箭头
            this.DoPre();
          } else if (keyCode == 38) {
            //上箭头
            this.setZoom(1);
          } else if (keyCode == 39) {
            //右箭头
            this.DoNext();
          } else if (keyCode == 40) {
            //下箭头
            this.setZoom(-1);
          } else if (keyCode > 48 && keyCode < 51) {
            //1 2
            this.SetStatus(keyCode - 48);
          } else if (keyCode == 112) {
            //F1
            if (this.help_visible == true) {
              this.helpClose();
            } else {
              this.HelpOpen();
            }
          } else if (keyCode == 13) {
            this.DoUpload();
          } else if (keyCode == 32) {
            //空格
            // if(this.showMode==1){this.Switch()}
          }
          // else if (keyCode ==192) { //`
          //   this.SetStatus(0)
          // }
        }
        e.stopPropagation();
        e.preventDefault();
      };
    },
    onChange_auto() {
      this.auto_next = !this.auto_next;
      this.$nextTick(() => {
        this.$refs.Change_auto.blur();
      });
    },
    GetActiveTasks() {
      this.activeTasks = [];
      this.activeTask = "";
      this.activeFeatrueProps = {};
      this.HandlData = [];
      let qs = {
        pagesize: 10,
        pagenum: 1,
        status: 0,
        optype: this.task_type,
      };
      // qs.name = this.$store.state.user.user.fullname;
      this.$common_apis.axios_get("/search_task?", qs).then((result) => {
        if (result) {
          this.activeTasks = result.data;
          if (this.activeTasks.length > 0) {
            this.activeTask = this.activeTasks[0].mergeid;
            // this.GetTasks()
            this.fetchUserNames();
          }
        }
      });
    },
    // 选择任务类型
    SelectType(value, Option) {
      this.GetActiveTasks();
    },
    GetTasks(pagenum = 1) {
      this.tasks = [];
      this.activeFeatrueProps = {};
      let qs = {
        pagesize: this.tasknum,
        pagenum: this.currentPage || pagenum,
        mergeid: this.activeTask,
        name: this.selectedName || this.$store.state.user.user.fullname,
        status: this.resultType || "-1",
        optype: this.task_type,
      };
      this.$common_apis.axios_get("/search?", qs).then((result) => {
        if (result) {
          let tasks_data = result.data;
          this.page = result.page;
          this.totalRecords = result.page.count;
          tasks_data.forEach((_featrue, index) => {
            _featrue.key = index;
            _featrue.other = _featrue.properties.other;
          });
          this.tasks = tasks_data;
          this.DataHandling();
          if (this.tasks.length > 0) {
            this.nextFeatrue(0);
          }
        }
      });
    },
    DataHandling() {
      let arrLength = this.tasks.length; // 数组长度
      let num = 7; // 每页显示 10 条
      let newArr = [];
      let index = 0;
      for (let i = 0; i < arrLength; i++) {
        if (i % num === 0 && i !== 0) {
          // 可以被 10 整除
          newArr.push(this.tasks.slice(index, i));
          index = i;
        }
        if (i + 1 === arrLength) {
          newArr.push(this.tasks.slice(index, i + 1));
        }
      }
      this.HandlData = newArr.map((item) => {
        let items = item.map((task) => {
          if (task && task.properties) {
            task.properties.status = this.resultType;
          }
          return task;
        });

        return items;
      });
    },
    TaskSelectChange() {
      this.GetTasks();
    },
    nextFeatrue(index = 0) {
      if (index > this.tasks.length - 1) {
        return;
      }
      let Featrue = this.tasks[index];
      this.activeFeatrueProps = Featrue.other;
      this.doKey = index;
      Bus.emit("set_img_Featrue", Featrue);
    },
    DoNext() {
      if (this.doKey < this.tasks.length - 1) {
        this.nextFeatrue(this.doKey + 1);
      }
    },
    DoPre() {
      if (this.doKey > 0) {
        this.nextFeatrue(this.doKey - 1);
      }
    },
    setZoom(zoom) {
      Bus.emit("set_zoom", zoom);
    },
    SetStatus(status) {
      if (this.tasks.length > 0 && this.tasks[this.doKey]) {
        this.tasks[this.doKey].properties.status = status;
        if (this.auto_next) {
          this.DoNext();
        }
      }
    },
    GetStautsCheck() {
      if (this.tasks.length > 0) {
        let finds = this.tasks.filter((_task) => {
          return _task.properties.status < 0;
        });
        if (finds.length > 0) {
          return true;
        } else {
          return false;
        }
      } else {
        return true;
      }
    },
    DoUpload() {
      let _GetStauts = this.GetStautsCheck();
      if (_GetStauts) {
        this.$message.info("请全部解译后再上传");
        return;
      }
      let code_status = [];
      this.tasks.forEach((_task, index) => {
        code_status.push({
          status: _task.properties.status,
          code: _task.properties.other.JVBH,
          taskid: _task.properties.taskid,
        });
      });
      this.$common_apis.axios_post(
        "/update_user?",
        {
          mergeid: this.activeTask,
          name: this.$store.state.user.user.fullname,
          code_status: JSON.stringify(code_status),
          optype: this.task_type,
        },
        true
      ).then((res) => {
        if (res) {
          this.$message.success(`更新成功`);
          Bus.emit("clearmap", 1);
          Bus.emit("clearmap", 2);
          this.GetActiveTasks();
        }
      });
    },
    GetTitle(map) {
      if (map == 1) {
        return this.activeFeatrueProps.QSX ? this.activeFeatrueProps.QSX : "";
      } else if (map == 2) {
        return this.activeFeatrueProps.HSX ? this.activeFeatrueProps.HSX : "";
      }
    },
    HelpOpen() {
      this.help_visible = true;
    },
    helpClose() {
      this.help_visible = false;
    },
    fetchUserNames() {
      this.$axios
        .get("/get_user_by_role?roleid=2c9380847b9ac53e017b9f365a1c44c2", {
          auth: "true",
        })
        .then((result) => {
          if (result) {
            this.userNames = result.data.result.filter((item) => {
              return item.org == this.currentOrg;
            });
            if (this.userNames.length > 0) {
              this.selectedName = this.userNames[0].fullname;
              this.GetTasks();
            }
          }
        });
    },
    NameSelectChange(name) {
      this.selectedName = name;
      this.GetTasks();
    },
    onChangeResultType() {
      // this.resultType=type
      this.GetTasks();
    },
    changePage() {
      this.GetTasks();
    },
    onChangeOrg() {
      // this.GetTasks();
      this.selectedName = ""
      this.fetchUserNames();
    },
    async getAllData() {
      let promiseArray = [];
      this.userTables = [];
      for (let index = 0; index < this.userNames.length; index++) {
        const username = this.userNames[index].fullname;
        let qs = {
          pagesize: this.tasknum,
          pagenum: this.currentPage,
          mergeid: this.activeTask,
          name: username,
          status: this.resultType || "-1",
          optype: this.task_type,
        };
        let userTable = {
          data: {
            unfinish: 0,
            nochange: 0,
            changed: 0,
          },
          username,
        };
        this.userTables.push(userTable);
        for (const resultType of ["1", "2", "-1"]) {
          qs.status = resultType;
          this.$common_apis.axios_get("/search?", qs).then((result) => {
            if (result) {
              // let obj = { resultType, count: result.page.count };
              let key =
                resultType == "-1"
                  ? "unfinish"
                  : resultType == "1"
                    ? "nochange"
                    : resultType == "2"
                      ? "changed"
                      : "";
              userTable.data[key] = result.page.count;
              // this.totalRecords = result.page.count;
              // tasks_data.forEach((_featrue, index) => {
              //   _featrue.key = index;
              //   _featrue.other = _featrue.properties.other;
              // });
              // this.tasks = tasks_data;
              // this.DataHandling();
              // if (this.tasks.length > 0) {
              //   this.nextFeatrue(0);
              // }
            }
          });
        }
        this.modalVisible = true;
        // this.$common_apis.axios_get("/search?", qs).then((result) => {
        //   if (result) {
        //     let tasks_data = result.data;
        //     this.page = result.page;
        //     this.totalRecords = result.page.count;
        //     tasks_data.forEach((_featrue, index) => {
        //       _featrue.key = index;
        //       _featrue.other = _featrue.properties.other;
        //     });
        //     this.tasks = tasks_data;
        //     this.DataHandling();
        //     if (this.tasks.length > 0) {
        //       this.nextFeatrue(0);
        //     }
        //   }
        // });
      }
    },
    showModal() {
      this.modalVisible = true;
    },
    handleOk(e) {
      console.log(e);
      this.modalVisible = false;
    },
    taskSelectChange() {
      // this.selectedName = ""
      this.GetTasks();
    }
  },
  destroyed() {
    document.onkeydown = undefined;
  },
};
</script>

<style scoped>
.task-type {
  width: 300px;
  height: 60px;
  position: fixed;
  margin-left: 30%;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 8px;
  z-index: 999;
}
</style>